const Router = require('koa-router')
const router = new Router({
    prefix: '/cms/file'
});
const fs = require('fs')

const COS = require('cos-nodejs-sdk-v5');
const cos = new COS({
    SecretId: 'AKIDm2B9yf6CcvY4RdBwNhpqiPzOvOgqD218',
    SecretKey: 'pk086ELNK7mZO3e8ShmhRXYOApMix8A1'
});


const uploader = (file,file_name, type) => {
    return new Promise((resolve, reject) => {

        cos.putObject({
            Bucket: 'lg-cj4cvlgk-1256897650',
            Region: 'ap-shanghai',
            Key: `cloud/${file_name}.${type}`,  // 这里传入前缀
            Body: fs.createReadStream(file.path),
        }, function (err, data) {
           if(err) resolve(err)
           else resolve(data)
           reject()
        });
    })
}

router.post('/', async ctx => {

    const file = ctx.request.files.file;
    const type = file.type.split('/')[1]
    const file_name = Math.random() * 1000 + new Date().valueOf() + '';
    const res = await uploader(file,file_name,type)

    if(res.Location){
        ctx.body = {
            data: 'https://' + res.Location,
            msg: 'ok'
        }
    }else{
        ctx.body = {
            data: null,
            msg: 'err'
        }
    }
})




module.exports = router;